package com.guoxw.ibinderdemo.server;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.guoxw.ibinderdemo.IMyAidl;
import com.guoxw.ibinderdemo.bean.Person;

import java.util.ArrayList;
import java.util.List;

public class MyAIDLService extends Service {

    private ArrayList<Person> persons;

    public MyAIDLService() {
    }
    /**
     * 创建生成的本地 Binder 对象，实现 AIDL 制定的方法
     */
    private IBinder personManager = new IMyAidl.Stub() {
        @Override
        public void addPerson(Person person) throws RemoteException {
            synchronized (this) {
                if (persons == null) {
                    persons = new ArrayList<>();
                }

                if (persons == null) {
                    return;
                }


                persons.add(person);
                Log.e("Server", "person: " + person.toString());
                Log.e("Server", "list persons: " + persons.toString());
            }
        }

        @Override
        public List<Person> getPersonList() throws RemoteException {
            synchronized (this){

                if (persons!=null){
                    return persons;
                }
                return new ArrayList<>();
            }
        }
    };

    /**
     * 客户端与服务端绑定时的回调，返回 mIBinder 后客户端就可以通过它远程调用服务端的方法，即实现了通讯
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent) {
        persons = new ArrayList<>();
        Log.i("MyAIDLService","=========onBind===");
      return personManager;
    }
}